/**----------------------------------------------------------*/
/** JS:  cmi_variety_list.js（商品管理--商品分类）           */
/**----------------------------------------------------------*/

var tipc = 'GOODS_VARIETY';
var tipc_categroy = 'GOODS_CATEGROY';
var tipc_prop = 'GOODS_CATEGROY_PROPERTIES';

var win = null;

var add = function() {
	try {
		var div = getEditDiv(null);
		win = MyUtils._getToolbarWin("dataPanel", "dateEdit", div, submitAdd, panel + "--添加","保存提交");
		win.window({
			width:790,
			height:380,
			modal: true
		});
		repainVariety(null);
	} catch (e) {
		showJsException(e);
	}
};

var modify = function() {
	try{
		var record = $('#dataPanel').treegrid("getSelected");
		if(record == null) {
			return;
		}
		var div = getEditDiv(record);
		win = MyUtils._getToolbarWin("dataPanel", "dateEdit", div, submitModify, panel +"--修改","保存提交");
		win.window({
			width:790,
			height:380,
			modal: true
		});
		repainVariety(record);
	} catch(e) {
		showJsException(e);
	}
};

var remove = function() {
	try{
		var rows = $('#dataPanel').treegrid("getSelected");
		if(rows == null) {
			MyUtils.waring(_empty_select);
			return;
		}
		var data = { data:rows.uuid
			    ,st:tipc
			    ,msg:rows.varName
		};
		$.messager.confirm(_msg_sys,MyUtils.valueAlign(_remove_confirm,"left"), function(r) {
			if (r) {
				MyUtils.openMask(_msg_process,$('#t2'));
				MyUtils.sendPost("impl_remove/backRemove.adm",data,function(rets){
					try{
						MyUtils.hiddenMask($('#t2'));
						var res = MyUtils.toJsonObject(rets);
						if(res.error == '0') {
							MyUtils.info(res.msg);
							$('#dataPanel').treegrid("clearSelections");
							$('#dataPanel').treegrid({url:"impl_search/searchObjectList.ajax?qy=&st=" + tipc});
						} else {
							MyUtils.error(res.msg);
						}
					} catch (e) {
						showJsException(e);
					}
				});
			}
		});
		
	} catch(e) {
		showJsException(e);
	}
};

var move = function(){
	alert("操作功能不明确");
};


var initPanel = function() {
	try {
		var columns = [ {field : 'varName',title : '分类名称',width : 150,align : 'left',formatter:function(value){
							return MyUtils.valueAlign(value,"left");
						}}
						,{field : 'goodsCt',title : '商品数量',width :90,align : 'center'}
						,{field : 'varUnit',title : '数量单位',width : 120,align : 'center'}
						,{field : 'varNav',title : '导航栏',width : 100,align : 'center',formatter:function(value){
							return '<img alt="OK" src="'+(value =='0' ? noPic:okPic) +'" style="border: 0px;">';
						}}
						,{field : 'varShow',title : '是否显示',width : 100,align : 'center',formatter:function(value){
							return '<img alt="OK" src="'+(value =='0' ? noPic:okPic) +'" style="border: 0px;">';
						}}
						,{field : 'varPrice',title : '价格分级',width :90,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"center");}}
						,{field : 'varSort',title : '排序',width :90,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"left");}}
					];
		$('#dataPanel').treegrid({
			title:panel,
			iconCls:'icon-save',
			method:'POST',
			fit:true,
			url:"impl_search/searchObjectList.ajax?qy=&st=" + tipc,
			nowrap: false,
			fitColumns:true,
			collapsible:true,
			idField:'uuid',
			treeField:'varName',
			frozenColumns:[{field : 'uuid',title :'',width : 20,align : 'left'}],
			animate:true,
			columns:[columns],
			toolbar:toolbars,
			loadMsg : '正在加载信息,请稍等...',
			onDblClickRow : function(row) {
				$('#dataPanel').treegrid("clearSelections");
				$('#dataPanel').treegrid("select",row.uuid);
				modify();
			},
			onBeforeExpand:function(row) {
				$('#dataPanel').treegrid({url:null});
			}
		});
	} catch (e) {
		showJsException(e,"数据加载失败!");
	}
};

$(function(){
	initPanel();
});

var submitAdd = function(){
	try {
		var dt = editValidator();
		if(dt != null) {
			var data = {dt:dt,st:tipc};
			MyUtils.openMask(_msg_process,win);
			submitDate("impl_add/backAdd.adm",data);
		}
	} catch (e) {
		MyUtils.hiddenMask(win);
		showJsException(e,_msg_fail);
	}
};

var submitModify = function(){
	try {
		var dt = editValidator();
		if(dt != null) {
			var data = {dt:dt,st:tipc,qy:"[]"};
			$.messager.confirm(_msg_sys,MyUtils.valueAlign(_modify_confirm,"left"), function(r) {
				if(r) {
					MyUtils.openMask(_msg_process,win);
					submitDate("impl_modify/backModify.adm",data);
				}
			});
		}
	} catch (e) {
		MyUtils.hiddenMask(win);
		showJsException(e,_msg_fail);
	}
};

var editValidator = function(){
	var record = {
			 uuid:$('#uuid').val()
			,varName:$('#varName').val()
			,varUp:$('#varUp').val()
			,varUnit:$('#varUnit').val()
			,varSort:$('#varSort').val()
			,varShow:$('input[name="dm1Show"]:checked').val()
			,varNav:$('input[name="dm1Nav"]:checked').val()
			,varHome:''
			,varProp:''
			,varPrice:$('#varPrice').val()
			,varCss:$('#varCss').val()
			,varKeyword:$('#varKeyword').val()
			,varDesc:$('#varDesc').val()
		};
	var vals = new Array();
	var home = $('input[name="dm6"]:checked');
	for(var i = 0; i < home.length; i++) {
		vals.push(home[i].value);
	}
	record.varHome = vals.toString();
	
	vals = new Array();
	var prop = $('select[id*="s_props"]');
	for(var i = 0; i < prop.length; i++) {
		var sid = prop[i].id;
		var pid = "p" + sid.substr(1);
		var sval = $('#'+sid).combobox("getValue");
		var pval = $('#'+pid).combobox("getValue");
		if(sval == '0' || pval =='0') {
			continue;
		} else if ((sval == '0' && pval !='0') || (sval != '0' && pval =='0')) {
			MyUtils.info("请选择筛选属性");
			return null;
		}
		vals.push('{"sval":"'+sval+'","pval":"'+pval+'"}');
	}
	record.varProp = "[" + vals.toString() + "]";
	
	//验证用户账号
	if(MyUtils.isEmpty(record.varName)) {
		MyUtils.waring("分类名称不能为空");
		return null;
	}
	if(!(MyUtils.isInt(record.varPrice) && (record.varPrice <=10 && record.varPrice >=0))) {
		MyUtils.waring("价格区间个数应该在0-10之间");
		return null;
	}
	return MyUtils.toJsonStr(record);
};

var submitDate = function(url,data) {
	MyUtils.sendPost(url,data,function(msg){
		try{
			MyUtils.hiddenMask(win);
			var res = MyUtils.toJsonObject(msg);
			if(res.error == '0') {
				MyUtils.info(res.msg);
				if(win)win.window('close');
				$('#dataPanel').treegrid("clearSelections");
				$('#dataPanel').treegrid({url:"impl_search/searchObjectList.ajax?qy=&st=" + tipc});
			} else {
				MyUtils.error(res.msg);
			}
		} catch (e) {
			MyUtils.hiddenMask(win);
			MyUtils.error(_msg_fail);
		}
	});
};

var getEditDiv = function(record) {
	var div= '<table cellspacing="2" cellpadding="6" id="dateEdit">'
		+'<tbody>'
		+'<tr>'
		+'<th align="right" width=200>分类名称：</th>'
		+'<td align="left" width=500>'
		+'<input type="hidden" id="uuid" value="" >'
		+'<input type="text"  maxlength="120" id="varName" style="width: 288px;" value=""><label class="requre_field">*</label>'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200>上级分类：</th>'
		+'<td align="left">'
		+'<select id="varUp" style="height:20px;border: 1px solid #99BBE8;width: 150px;">'
		+'</select>'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200>数量单位：</th>'
		+'<td align="left" width=500>'
		+'<input type="text"  maxlength="120" id="varUnit" style="width: 288px;" value="">'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200>排序：</th>'
		+'<td align="left" width=500>'
		+'<input type="text"  maxlength="5" id="varSort" style="width: 288px;" value="50">'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200>是否显示：</th>'
		+'<td align="left">'
		+'<input type = "radio" name="dm1Show"  value="1">是</input>'
		+'<input type = "radio" name="dm1Show"  value="0">否</input>'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200>是否显示在导航栏:</th>'
		+'<td align="left">'
		+'<input type = "radio" name="dm1Nav"  value="1">是</input>'
		+'<input type = "radio" name="dm1Nav"  value="0">否</input></td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200>设置为首页推荐:</th>'
		+'<td align="left">'
		+'<input type = "checkbox" name="dm6"  value="1">精品</input>'
		+'<input type = "checkbox" name="dm6"  value="2">最新</input>'
		+'<input type = "checkbox" name="dm6"  value="3">热门</input>'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200 valign="top">筛选属性：</th>'
		+'<td align="left">'
		+'<div>'
		+'<a href="javascript:void(0);" id="propAdd">[+]</a>'
		+'<select id="s_props" style="height:20px;border: 1px solid #99BBE8;width: 150px;">'
		+'<option value="0">请选择商品类型</option>'
		+'</select>'
		+'<select id="p_props" properties="field" style="height:20px;border: 1px solid #99BBE8;width: 150px;">'
		+'<option value="0">请筛选属性</option>'
		+'</select>'
		+'</div>'
		+'<div id="props"></div>'
		+'<div style="color:gray;">筛选属性可在前分类页面筛选商品。</div>'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200 valign="top">价格区间个数:</th>'
		+'<td align="left"><input type="text"  maxlength="2" id="varPrice" style="width: 288px;" value="0">'
		+'<div style="color:gray;">该选项表示该分类下商品最低价与最高价之间的划分的等级个数，填0表示不做分级，最多不能超过10个。</div>'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200 valign="top">分类的样式表文件:</th>'
		+'<td align="left"><input type="text"  maxlength="120" id="varCss" style="width: 288px;" value="">'
		+'<div style="color:gray;">您可以为每一个商品分类指定一个样式表文件。例如文件存放在 themes 目录下则输入：themes/style.css。</div>'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200 valign="top">关键字:</th>'
		+'<td align="left"><input type="text"  maxlength="120" id="varKeyword" style="width: 288px;" value="">'
		+'</td>'
		+'</tr>'
		+'<tr>'
		+'<th align="right" width=200 valign="top">分类描述:</th>'
		+'<td align="left"><textarea rows="6" cols="31" id="varDesc" name="varDesc" style="width: 300px;"></textarea>'
		+'</td>'
		+'</tr>'
		+'</tbody>'
		+'</table>';
	return div;
};

var repainVariety = function(record){
	
	var tab = function(times) {
		var nbsp = '&nbsp;&nbsp;&nbsp;&nbsp;';
		var space = '';
		while(times > 0) {
			space +=nbsp;
			times--;
		}
		return space;
	};
	var varietyOption = function(datas,index) {
		var div = "";
		for(var i=0;i<datas.length;i++) {
			div +='<option value="'+datas[i].uuid+'">'+(tab(index) + datas[i].varName)+'</option>';
			if(datas[i].children && datas[i].children.length > 0) {
				div += varietyOption(datas[i].children,(index +1));
			}
		}
		return div;
	};
	
	var appendCategroy = function(divId) {
		var div = '<div id="'+divId+'" style="margin-top:5px;">'
		+'<a href="javascript:void(0);" onclick="javascript:$(this).parent().remove();" style="margin-right:5px;">[-]</a>'
		+'<select id="s_'+divId+'" style="height:20px;border: 1px solid #99BBE8;width: 150px;">'
		+'</select>'
		+'<select id="p_'+divId+'" properties="field" style="height:20px;border: 1px solid #99BBE8;width: 150px;">'
		+'</select>'
		+'</div>';
		return div;
	};
	
	var loadCategroy = function(sufix,categroy,fiels) {
		$('#s_' + sufix).combobox({
			 url:"impl_search/searchObjectList.ajax?st="+tipc_categroy+"&qy=" 
			,valueField:"uuid" 
			,textField:"categroy"
		    ,onSelect:function(record) {
		    	$('#p_' + sufix).combobox({
		    		url:"impl_search/searchObjectList.ajax?st="+tipc_prop+"&qy=" + record.uuid
		    	});
		    }
			,value:(categroy ? categroy : '0')
		});
		
		$('#p_' + sufix).combobox({
			url:"impl_search/searchObjectList.ajax?st="+tipc_prop+"&qy=" + (categroy ? categroy : '0')
			,valueField:"uuid" 
			,textField:"proName"
			,value:(fiels ? fiels : '0')
		});
	};
	
	$('input[name="dm1Show"][value='+(record && !MyUtils.isEmpty(record.varShow)? record.varShow : 1)+']').attr("checked",true);
	$('input[name="dm1Nav"][value='+(record && !MyUtils.isEmpty(record.varNav)? record.varNav : 0)+']').attr("checked",true);
	$('#props').empty();
	
	//所有分类
	var datas = $('#dataPanel').treegrid("getData");
	var varUp_div = '<option value="0">顶级分类</option>';
	varUp_div +=varietyOption(datas,0);
	$('#varUp').append(varUp_div);
	
	//赋予输入框
	if(record) {
		$('#uuid').val(record.uuid);
		$('#varName').val(record.varName);
		$('#varUnit').val(record.varUnit);
		$('#varSort').val(record.varSort);
		$('#varPrice').val(record.varPrice);
		$('#varCss').val(record.varCss);
		$('#varKeyword').val(record.varKeyword);
		$('#varDesc').val(record.varDesc);
		$('#varUp').val(record.varUp);
		
		//属性
		var props = record.varProp;
		if(!MyUtils.isEmpty(props) && props !='[]') {
			var div ='';
			props = MyUtils.toJsonObject(props);
			for(var i = 0; i < props.length; i++) {
				if(i == 0) {
					loadCategroy('props',props[i].sval,props[i].pval);
					$('#s_props').combobox("select",props[i].sval);
					$('#p_props').combobox("select",props[i].pval);
				} else {
					div +=appendCategroy('props_'+(i-1));
				}
			}
			if(div !=''){
				$('#props').append(div);
				for(var i = 1; i < props.length; i++) {
					var id = 'props_'+(i-1);
					loadCategroy(id,props[i].sval,props[i].pval);
					$('#s_' + id).combobox("select",props[i].sval);
					$('#p_' + id).combobox("select",props[i].pval);
				}
			}
		} else {
			loadCategroy('props',null,null);
		}
		//首页推荐
		var home = record.varHome;
		if(!MyUtils.isEmpty(home)) {
			var splits = home.split(",");
			for(var i = 0;i < splits.length; i++) {
				$('input[name="dm6"][value="' + splits[i] + '"]').attr("checked",true);
			}
		}
		
	} else {
		$('#varUp').val(0);
		loadCategroy('props',null,null);
	}
	
	$('#propAdd').live('click',function(){
		//验证筛选属性是否都已经选择
		var childs = $('select[id*="p_props"]');
		for(var i = 0;i < childs.length; i++){
			var lid = childs[i].id;
			var sid = "p" + lid.substr(1);
			var pval = $('#'+sid).combobox("getValue");
			var curt = $('#'+lid).combobox("getValue");
			if(curt == '0' || pval == '0') {
				MyUtils.info("请选择筛选属性");
				return;
			}
		}
		var divId ="props_"+$('#props').children().length;
		$('#props').append(appendCategroy(divId,null,null));
		loadCategroy(divId);
	});
};
